package com.framework.base.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.framework.base.constant.ActionConstants;
import com.framework.base.constant.WebConstants;
import com.framework.base.dao.BaseDao;
import com.framework.base.dao.DataOpVo;
import com.framework.base.dao.IDManager;
import com.framework.base.dialect.Dialect;
import com.framework.base.dialect.OracleDialectImp;
import com.framework.base.struts.BaseVo;
import com.framework.base.struts.Result;
import com.framework.base.taglib.page.Pagination;
import com.framework.base.util.Assert;
import com.framework.base.util.QueryUtil;
import com.framework.base.util.StringUtil;
import com.framework.base.util.SysConfUtil;
import com.framework.main.sys.attachment.dao.AttachmentDao;
import com.framework.main.sys.attachment.domain.AttachmentVo;

/**
 * @Copyright @ 2011 All right reserved
 * @version 创建时间：Created on 2011-7-11
 * @author 作者：Create by HYH
 * @Email: huyinhui2012@gmail.com
 * @description 业务处理的基类
 * 更新内容有:
 * 1.改变toUpdate方法中的调用sql名   改名为getById
 * 2.改变toView方法中的调用sql名   改名为getById
 * 3.修改tolist方法中的查询能参数对象 由原来的组装squall的string参数变为map
 * 以防止sql注入
 */
public class BaseServiceImp implements BaseService {
	private BaseDao baseDao; // 数据操作的基类对象
	private Dialect dialect=new OracleDialectImp(); //分页查询的方言接口对象
	private AttachmentDao attachmentDao;  //附件对象
	private int rowsPerPage=SysConfUtil.getPageSize();//分页行数 默认行数在system.properties中配置

	/**
	 * 取得日志对象
	 * 
	 * @return 返回日志对象
	 */
	public Logger getLogger() {
		Logger logger = Logger.getLogger(getClass()); // 作为日志的公用对象
		return logger;
	}

	/**
	 * 用于处理数据新增前的准备
	 * 
	 * @param cfg
	 */
	public String toInsert() throws Exception {
		return ActionConstants.INPUT;
	}

	/**
	 * 用于处理数据新增业务
	 * 
	 * @param cfg
	 * @return
	 */
	public String doInsert(BaseVo vo) throws Exception {
		if (StringUtil.isNullorEmpty(vo.getIdf())||"null".equals(vo.getIdf())) {
			vo.setIdf(IDManager.generateID());
		}
		if (vo.getDatasortNumf() == 0) {
			vo.setDatasortNumf(System.currentTimeMillis());
		}
		this.getBaseDao().doUpdate("doInsert", vo);
		return ActionConstants.RELOAD;
	}

	/**
	 * 用于处理数据新增业务和保存附件的数据
	 * @author lbx
	 * @createTime 2011-06-18
	 * @param cfg
	 * @return
	 */
	public String doInsert(BaseVo vo,List<AttachmentVo> attachList) throws Exception{
		if (StringUtil.isNullorEmpty(vo.getIdf())||"null".equals(vo.getIdf())) {
			vo.setIdf(IDManager.generateID());
		}
		if (vo.getDatasortNumf() == 0) {
			vo.setDatasortNumf(System.currentTimeMillis());
		}
		this.getBaseDao().doUpdate("doInsert", vo);
		//判断是否有附件

		if(attachList!=null&&attachList.size()>0){
			String idf=StringUtil.nullToEmpty(vo.getIdf());
			if(idf.length()>0){
				for (AttachmentVo attachmentVo : attachList) {
					attachmentVo.setForeignIdf(idf);
					if (StringUtil.isNullorEmpty(attachmentVo.getIdf())||"null".equals(attachmentVo.getIdf())) {
						attachmentVo.setIdf(IDManager.generateID());
					}
					if (attachmentVo.getDatasortNumf() == 0) {
						attachmentVo.setDatasortNumf(System.currentTimeMillis());
					}
					attachmentDao.doInsert("doInsert",attachmentVo);
				}
			}
		}
		return ActionConstants.RELOAD;
    }
	/**
	 * 用于处理数据删除的业务
	 * @param cfg
	 * @return
	 */
	public String doDelete(String[] pks) throws Exception {
		if (pks != null && pks.length > 0) {
			this.getBaseDao().doDelete("doDelete", pks);
		}
		return ActionConstants.RELOAD;
	}

	/**
	 * 用于处理数据修改的业务
	 * @param cfg
	 * @return
	 */
	public String doUpdate(BaseVo vo) throws Exception {
		this.getBaseDao().doUpdate("doUpdate",vo);
		return ActionConstants.RELOAD;
	}
	/**
	 * 用于修改原有的数据，同时添加附件
	 * @param cfg
	 * @return
	 */
	public String doUpdate(BaseVo vo,List<AttachmentVo> attachList) throws Exception {
		this.getBaseDao().doUpdate("doUpdate",vo);
		//1.判断是否有附件，如存在则添加
		if(attachList!=null&&attachList.size()>0){
			String idf=StringUtil.nullToEmpty(vo.getIdf());
			if(idf.length()>0){
				for (AttachmentVo attachmentVo : attachList) {
					attachmentVo.setForeignIdf(idf);
					if (StringUtil.isNullorEmpty(attachmentVo.getIdf())||"null".equals(attachmentVo.getIdf())) {
						attachmentVo.setIdf(IDManager.generateID());
					}
					if (attachmentVo.getDatasortNumf() == 0) {
						attachmentVo.setDatasortNumf(System.currentTimeMillis());
					}
					attachmentDao.doInsert("doInsert",attachmentVo);
				}
			}
		}
		return ActionConstants.RELOAD;
	}

	/**
	 * 用于获取数据并进行查看

	 * 
	 * @param cfg
	 * @return
	 */
	public Result getById(String pk) throws Exception {
		Assert.notNull(pk, "fid不能为空");
		BaseVo vo = (BaseVo) this.getBaseDao().getById("getById", pk);
		return new Result(ActionConstants.SUCCESS,vo);
	}

	/**
	 * 用于组合sql
	 * @param paramsMap
	 * @param orderByFields
	 * @param orderType
	 * @return
	 * @throws Exception
	 */
	public String populatePageHQL(Map<String,Object> paramsMap,String orderByFields,
			String orderType) throws Exception{
		StringBuffer queryString=new StringBuffer();
		queryString.append(QueryUtil.generateQuerySql(paramsMap));
		queryString.append(" order by ");
		if(!StringUtil.isNullorEmpty(orderByFields)&&!StringUtil.isNullorEmpty(orderType)){
			queryString.append(orderByFields).append(" ").append(orderType);
		}else{
			queryString.append(" datasortNumf desc");
		}
		return queryString.toString();
	}
	/**
	 * 用于查询并显示分页数据

	 * 
	 * @param cfg
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Result toList(Map<String, Object> paramsMap)throws Exception {
		//1.获取分页相关参数
		String orderByfields=StringUtil.getStringFromObj(paramsMap.get(WebConstants.ORDERFIDS));
		String orderType=StringUtil.getStringFromObj(paramsMap.get(WebConstants.ORDERTYPE));
		String currentPage=StringUtil.getStringFromObj(paramsMap.get(WebConstants.CURRENTPAGE));
		String changeType=StringUtil.getStringFromObj(paramsMap.get(WebConstants.CHANGETYPE));
		
		//2.获取组装的sql
		String queryString=QueryUtil.generateQuerySql(paramsMap);
		//查询记录总数
		int totalCount=this.getBaseDao().getTotalPageCount("getTotalPageCount",getDialect().populatePageHQL(queryString,this.getBaseDao().getNameSpace()));
		//3.创建分页对象 并对数据进行计算
		Pagination page=new Pagination(totalCount,getRowsPerPage());
		page.doPagination(changeType, currentPage);
		
		//4.查询数据
		List<BaseVo> list = (List<BaseVo>) this.getBaseDao().toList("toList",getDialect().populatePageHQL2(queryString,orderByfields,orderType,page,this.getBaseDao().getNameSpace()));
		page.setData(list);
		return new Result(ActionConstants.SUCCESS,page);
	}
	
	/**
	 * 验证指定条件下的数据是否重复
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author lbx
	 * @createTime 2011-07-01
	 */
	@SuppressWarnings("rawtypes")
	public List toCheckData(String sql)throws Exception{
		return this.getBaseDao().queryForList("toList",sql);
	}
	
	
	/**
	 * 判断验证指定字段的值是否重复

	 * @author lbx
	 * @ceateTime 2011-07-01
	 */
	public String toDduplicateCode(String classVo,String columns,String keyColumn,String selectType,String[] columnValue){
		getLogger().info("columns:"+columns);//验证字段列表
		getLogger().info("keyColumn:"+keyColumn);//表主键

		getLogger().info("selectType:"+selectType);//查询方式
		Map<String, String> paramMap = new HashMap<String, String>();
		String[] columnArray = columns.split(",");
		if(columnValue.length!=columnArray.length){
			return "false";
		}
		for (int i=0;i<columnArray.length;i++){
			String value = columnValue[i];
			String  key=columnArray[i];
			getLogger().info("key="+key+"  value="+value);
			paramMap.put(key, value);
		}
		 
		if(StringUtil.nullToEmpty(selectType).equals("like")){
			selectType="like";
		}else{
			selectType="=";
		}
		Class cls=null;
		try {
			cls = Class.forName(classVo);
			String sql=QueryUtil.checkDuplicateSQL(cls,keyColumn,paramMap,selectType);
			getLogger().info("sql:"+sql);
			if(sql.length()>0){
				List list;
				try {
					list = this.toCheckData(sql);
					if(list!=null&&!list.isEmpty()){
						return "true";
					}else{
						return "false";
					}
				} catch (Exception e) {
					e.printStackTrace();
					return "false";
				}
			}else{
				return "false";
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return "false";
		}
	}
	



	public BaseDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	public int getRowsPerPage() {
		return rowsPerPage;
	}

	public void setRowsPerPage(int rowsPerPage) {
		this.rowsPerPage = rowsPerPage;
	}

	public AttachmentDao getAttachmentDao() {
		return attachmentDao;
	}

	public void setAttachmentDao(AttachmentDao attachmentDao) {
		this.attachmentDao = attachmentDao;
	}
	
	public Dialect getDialect() {
		return dialect;
	}

	public void setDialect(Dialect dialect) {
		this.dialect = dialect;
	}

	//批量处理数据的方法
	public void collectDataOpObj(String statementId,Object paramObj,String dataOpType,List<DataOpVo> dataOpVoList){
		DataOpVo vo=new DataOpVo();
		vo.setStatementId(statementId);
		vo.setParamObj(paramObj);
		vo.setDataOpType(dataOpType);
		dataOpVoList.add(vo);
	}
}
